package cn.jasonone.server;

import cn.jasonone.tio.tcp.config.properties.ServerProperties;
import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.tio.core.stat.GroupStat;
import org.tio.server.TioServer;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author xujie
 * @version 1.0
 * @date 2022/1/21 7:57
 */
@Data
public class TcpServer implements InitializingBean, DisposableBean {
    private final ServerProperties serverProperties;
    private final TioServer tioServer;

    public void start(String ip, int port) throws IOException {
        this.tioServer.start(ip, port);
    }

    public GroupStat getGroupStat() {
        return tioServer.getServerTioConfig().getGroupStat();
    }

    public void start() throws IOException {
        this.tioServer.start(serverProperties.getIp(), serverProperties.getPort());
    }

    public void stop() throws IOException {
        this.tioServer.stop();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.serverProperties.isAutoStart()) {
            this.start();
        }
        if(this.serverProperties.isAutoStop()){
            Runtime.getRuntime().addShutdownHook(new Thread(()->{
                try {
                    destroy();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }));
        }
    }

    @Override
    public void destroy() throws Exception {
        if(this.serverProperties.isAutoStop()){
            this.stop();
        }
    }
}
